package com.imstlife.vending.plus;

import android.content.Context;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;

import com.dwin.navy.serialportapi.com_zhongji;
import com.imstlife.vending.R;
import com.imstlife.vending.utils.Cof;
import com.imstlife.vending.utils.SharePersistent;
import com.imstlife.vending.utils.SharePersistentUtil;
import com.imstlife.vending.utils.T;

public class TmpHelper implements CompoundButton.OnCheckedChangeListener, RadioGroup.OnCheckedChangeListener, View.OnClickListener {


    private String TAG = "TmpHelper";


    private Context context;

    //温度控制开关
    private Switch tmpSwitch;

    //当前温度
    private TextView tvCurrentTmp;

    /**
     * 温度控制操作栏 默认隐藏
     */
    private RelativeLayout rlTmp;

    /**
     * 设置温度加减
     */
    private Button btnTmpAdd,btnTmpReduce;

    /**
     * 制冷 加热切换
     */
    private RadioGroup radioGroup;

    /**
     * LED灯条开关
     */
    private Switch switchLed;


    /**
     * 玻璃加热
     */
    private Switch switchHeatGlass;

    /** 当前设置温度 */
    private TextView tvSetTmp;

    /**
     * 温度控制自线程
     */
    private HandlerThread tmpHandlerThread ;
    /**
     * 自线程Handler
     */
    private Handler tmpHandler;
    /**
     * 主线程Handler
     */
    private Handler uiHandler;

    /**
     * 中吉串口API
     */
    private com_zhongji zhongjiSerial;


    public TmpHelper(Context context, Switch tmpSwitch, TextView tvCurrentTmp, RelativeLayout rlTmp, Button btnTmpAdd, Button btnTmpReduce, RadioGroup radioGroup, Switch switchLed, Switch switchHeatGlass, TextView tvSetTmp) {
        this.context = context;
        this.tmpSwitch = tmpSwitch;
        this.tvCurrentTmp = tvCurrentTmp;
        this.rlTmp = rlTmp;
        this.btnTmpAdd = btnTmpAdd;
        this.btnTmpReduce = btnTmpReduce;
        this.radioGroup = radioGroup;
        this.switchLed = switchLed;
        this.tvSetTmp = tvSetTmp;
        this.switchHeatGlass = switchHeatGlass;
        this.tmpSwitch.setOnCheckedChangeListener(this);
        this.switchLed.setOnCheckedChangeListener(this);
        this.switchHeatGlass.setOnCheckedChangeListener(this);
        this.radioGroup.setOnCheckedChangeListener(this);

        this.btnTmpAdd.setOnClickListener(this);
        this.btnTmpReduce.setOnClickListener(this);
        init();
    }

    /**
     * 初始化操作
     *
     * 打开子线程
     * 1.检查当前温度
     * 2.需要回显当前温控开关
     * 3.需要回显温度操作栏
     * 4.需要回显当前设置温度
     * 5.需要回显当前温度模式 制冷/加热
     * 6.需要回显当前LED状态
     * 7.需要回显当前玻璃加热状态
     * 8.为了确保机器与缓存设置项同步，发送 2、3、4、5、6、7
     */
    private void init() {

        if(tmpHandlerThread==null||!tmpHandlerThread.isAlive()){
            tmpHandlerThread = new TmpHandlerThread("tmpThread");
            tmpHandlerThread.start();
            tmpHandler = new Handler(tmpHandlerThread.getLooper());
            uiHandler = new Handler(Looper.getMainLooper());
        }



    }

    public void ref(){
        if(tmpHandler==null){
            return;
        }


        Log.i(TAG, "ref: ");
        tmpHandler.post(new Runnable() {
            @Override
            public void run() {
                startSerialPort();
                Log.i(TAG, " tmpHandler run() 当前线程: " + Thread.currentThread().getName());
                final String tmp = zhongjiSerial.checkTmp();

                uiHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        Log.i(TAG, " uiHandler run() 当前线程: " + Thread.currentThread().getName());
                        if (tmp != null) {
                            tvCurrentTmp.setText(tmp + "°C");
                            T.showShort(context,"当前温度："+tmp+"°C");
                        }

                        final boolean switchTmpBoolan = SharePersistentUtil.getSharePersistentBoolean(context, Cof.APP_IMAGE_CACHE, Cof.KEY_SWITCH_TMP);
                        final boolean switchLedBoolan = SharePersistentUtil.getSharePersistentBoolean(context, Cof.APP_IMAGE_CACHE, Cof.KEY_SWITCH_LED);
                        final boolean switchHeadGlassBoolan = SharePersistentUtil.getSharePersistentBoolean(context, Cof.APP_IMAGE_CACHE, Cof.KEY_SWITCH_HEAT_GLASS);

                        tmpSwitch.setChecked(switchTmpBoolan);
                        switchLed.setChecked(switchLedBoolan);
                        switchHeatGlass.setChecked(switchHeadGlassBoolan);
                    }
                });
            }
        });
    }



    private void startSerialPort(){
        String str = SharePersistentUtil.getSharePersistentString(context,"spnum");
        int iserial = Cof.SERIAL_PORT_NUM;
        if (str!=null&&!str.equals("")){
            iserial = Integer.parseInt(str);
        }
        zhongjiSerial  = com_zhongji.getInstance(iserial);
        zhongjiSerial.openSerialPort();
    }
    private void stopSerialPort(){
        if(zhongjiSerial!=null){
            zhongjiSerial.closeSerialPort();
        }
    }

    /**
     * 收尾工作
     */
    public void  onDestory(){

        stopSerialPort();

        if(uiHandler!=null){
            uiHandler.removeCallbacksAndMessages(null);
        }
        if(tmpHandler!= null){
            tmpHandler.removeCallbacksAndMessages(null);
        }
//
//        if(tmpHandlerThread != null ){
//            tmpHandlerThread.quit();
//            tmpHandlerThread = null;
//        }


    }

    /**
     * 更改温度控制开关
     * @param switchTmp
     */
    private void switchTmp(final boolean switchTmp){
        SharePersistentUtil.saveSharePersistent(context,Cof.APP_IMAGE_CACHE,Cof.KEY_SWITCH_TMP,switchTmp);
        //更新UI
        if(switchTmp){
            rlTmp.setVisibility(View.VISIBLE);
        }else{
            rlTmp.setVisibility(View.GONE);
        }
        //发送命令
        tmpHandler.post(new Runnable() {
            @Override
            public void run() {
               final boolean result= zhongjiSerial.updateTmpSwitch(switchTmp);
            }
        });
        //如果打开温控，同步设置温度、冷热模式
        if(switchTmp){
            final boolean switchCoolHotBoolan = SharePersistentUtil.getSharePersistentBoolean(context,Cof.APP_IMAGE_CACHE,Cof.KEY_SWITCH_COOL_HOT);
            if(switchCoolHotBoolan){
                radioGroup.check(R.id.rb_cool);
            }else{
                radioGroup.check(R.id.rb_hot);
            }
//            switchCoolHot(switchCoolHotBoolan);
            final int settingTmpValue = SharePersistentUtil.getSharePersistentInt(context,Cof.APP_IMAGE_CACHE,Cof.KEY_VALUE_TMP);
            sendChangeTmpValueCommand(settingTmpValue);

        }


    }

    private void switchLed(final boolean switchLed){
        SharePersistentUtil.saveSharePersistent(context,Cof.APP_IMAGE_CACHE,Cof.KEY_SWITCH_LED,switchLed);
        tmpHandler.post(new Runnable() {
            @Override
            public void run() {
                final boolean result = zhongjiSerial.updateLedSwitch(switchLed);
            }
        });

    }

    /**
     * 发送切换玻璃加热
     * @param switchHeadGlass
     */
    private void switchHeatGlass(final boolean switchHeadGlass){
        SharePersistentUtil.saveSharePersistent(context,Cof.APP_IMAGE_CACHE,Cof.KEY_SWITCH_HEAT_GLASS,switchHeadGlass);
        tmpHandler.post(new Runnable() {
            @Override
            public void run() {
                final boolean result = zhongjiSerial.updateHeatGlass(switchHeadGlass);
            }
        });

    }

    /**
     * 发送切换制冷/加热
     * @param switchCoolHot
     */
    private void switchCoolHot(final boolean switchCoolHot){
        SharePersistentUtil.saveSharePersistent(context,Cof.APP_IMAGE_CACHE,Cof.KEY_SWITCH_COOL_HOT,switchCoolHot);
        tmpHandler.post(new Runnable() {
            @Override
            public void run() {
                final boolean result = zhongjiSerial.updateCoolHot(switchCoolHot);
            }
        });

    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()){
            case R.id.switch_fg_more_setting_tmp:
                switchTmp(isChecked);
                break;
            case R.id.switch_fg_more_setting_led:
                switchLed(isChecked);
                break;
            case R.id.switch_fg_more_setting_heat_glass:
                switchHeatGlass(isChecked);
                break;
                default:
                    break;
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if(checkedId==R.id.rb_cool){
            switchCoolHot(true);
        }else{
            switchCoolHot(false);
        }
    }

    @Override
    public void onClick(View v) {
        final int settingTmpValue = SharePersistentUtil.getSharePersistentInt(context,Cof.APP_IMAGE_CACHE,Cof.KEY_VALUE_TMP);
        switch(v.getId()){
            case R.id.btn_fg_more_setting_add:
                if(settingTmpValue<10){
                    sendChangeTmpValueCommand(settingTmpValue+1);
                }
                break;
            case R.id.btn_fg_more_setting_reduce:
                if(settingTmpValue>-2){
                    sendChangeTmpValueCommand(settingTmpValue-1);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 改变温度显示 以及发送指令
     * @param tmp
     */
    private void sendChangeTmpValueCommand(final int tmp){
        SharePersistentUtil.saveSharePersistent(context,Cof.APP_IMAGE_CACHE,Cof.KEY_VALUE_TMP,tmp);
        tvSetTmp.setText(String.valueOf(tmp)+"°C");
        tmpHandler.post(new Runnable() {
            @Override
            public void run() {
                zhongjiSerial.updateTmpValue(tmp);
            }
        });
    }

}
